<template>
  <div>
    <!-- 蒙版层 -->
    <div class="pay-cover">
      <confirm-pay :orderSn = 'orderSnNum' @payConfirmFn = 'changePayConfirmFn' :payConfirm.sync="payConfirm" v-on:canclePay="togglePayConfirm" ref='confrimData'></confirm-pay>
      <!-- <pay-error></pay-error> -->
    </div>
    <div class="pay-content-wrapper">
      <div class="pay-details-wrapper">
        <!-- 订单详情 -->
        <div  class="stages-wrapper"  v-if='$route.query.requestBool == "1"'>
          <div class="title">
            分期单号：<span>{{stagesData.hireSn && stagesData.hireSn}}</span>
            套餐名称：<span>{{stagesData.order && stagesData.order.pack.name}}</span>
          </div>
          <p class="now-stages">当前期数：<span>{{stagesData.num && stagesData.num}}/{{stagesData.num && stagesData.order.hirePuchaesNum}}期</span></p>
          <p class="pay-price">
            ￥{{stagesData.hirePrice && stagesData.hirePrice }}<span class="yuan">元</span>
          </p>
        </div>
        <div v-if='$route.query.requestBool == "0"' class="pay-details-top">
          <p class="time-limit">
            请在
            <span class='time'>{{ timerFn }}&nbsp;&nbsp;前</span>完成支付！逾期订单将取消
          </p>
          <div class="pay-list">
                <span>订单号：</span>{{listData.orderSn }}
                <span>套餐名称：</span>{{pack.name }}
          </div>
          <p class="pay-price">
            <span v-if='listData.totalPayPrice!=null'>￥{{(listData.totalPayPrice*1).toFixed(2)}}</span><span class="yuan">元</span>
          </p>
        </div>
        <!-- 支付方式 -->
        <div class="pay-way-wrapper">
          <p class="text">支付平台</p>
          <div class="pay-icon-wrapper">
            <div class="align">
              <div class="alipay" @click="changeFn('alipayBool')" :class="{'on': payStyle.alipayBool}">
                <img src="../../images/zfblogo.png" class="icon-pic"/>
                <span class="tuij"><img src="../../images/tj.png"  height="32" width="34"/></span>
                <span class="topIcon icon-queren_y">
                  <span class="path1"></span><span class="path2"></span>
                </span>
              </div>
              <div class="wechat" @click="changeFn('wechatBool')" :class="{'on': payStyle.wechatBool}">
                <img src="../../images/wechatlogo.png" class="icon-pic"/>
                <span class="tuij"><img src="../../images/tj.png"  height="32" width="34"/></span>
                <span class="topIcon icon-queren_y">
                  <span class="path1"></span><span class="path2"></span>
                </span>
              </div>
            </div>
            <div class="align top">
              <div class="otherPay" @click="openOtherpay">其他支付方式<span :class="{roate:ywtPay==true}"><i class="icon-xiaosan_n"></i></span></div>
              <div v-if="ywtPay==true">
                <div class="yiwtpay" @click="changeFn('yiwtpayBool')" :class="{'on': payStyle.yiwtpayBool}">
                  <img src="../../images/ywtlogo.png" class="icon-pic"/>
                  一网通银行卡支付
                  <span class="topIcon icon-queren_y">
                    <span class="path1"></span><span class="path2"></span>
                  </span>
                </div>
                <div class="payyl">支持银联扫码支付</div>
              </div>
            </div>
          </div>
          <div class="btn-wrapper" :class="[ywtPay==true ? 'btnwrap':'btnwrap2']">
              <el-button :class="{checkColor: payStyle.alipayBool || payStyle.wechatBool || payStyle.yiwtpayBool}" @click="createPayOrder" :loading='loadingBool' class="submit">立即支付</el-button>
              <a @click.once="countConsult" :href="`http://wpa.qq.com/msgrd?v=3&uin=${QQNum}&site=qq&menu=yes`" target="_blank" class="consult">立即咨询</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  orderDetail,
  createPayOrder,
  createWechatPay,
  createAliPay,
  createYiwtPay,
  createPolymPay,
  findByHireSn,
  orderPaySuccess,
  statisticsSave
} from 'api/getData'
import confirmPay from './confirmPay'
import payError from './payError'
import { mapActions, mapGetters } from 'vuex'
export default {
  data() {
    return {
      payStyle: {
        alipayBool: false,
        wechatBool: false,
        yiwtpayBool:false
      },
      dataTime: '',
      listData: {},
      pack: {},
      timer: null,
      payConfirm: false,
      loadingBool: false,
      colorBool: false,
      stagesData: {},
      orderSnNum: '',
      payLoding: '',
      jsonRequestData:null,
      ywtPay:false
      // firstPayBool: true // 订单第一次进来
    }
  },
  computed: {
    ...mapGetters(['firstPayBool','currentUser', 'cityId', 'cityName', 'QQNum']),
    // 计算时间
    timerFn() {
      let data, YY, MM, DD, hh, mm, dataTime,
        addZero = n => n < 10 ? '0' + n : '' + n
      data = new Date(this.dataTime * 1 + 86400000)
      YY = data.getFullYear()
      MM = addZero(data.getMonth() + 1)
      DD = addZero(data.getDate())
      hh = addZero(data.getHours())
      mm = addZero(data.getMinutes())

      dataTime = `${YY}-${MM}-${DD}  ${hh}:${mm}`
      return dataTime
    },
    User() {
      return this.$store.state.currentUser;
    }
  },
  mounted() {

    if (this.$route.query.requestBool == '0') {
      this.getOrderDetail();
      this.orderSnNum = this.$route.query.orderSn
    } else {
      this.orderSnNum = this.$route.query.orderSn
      findByHireSn(this.$route.query.orderSn).then(res => {
        this.stagesData = res.data.msg
        this.pack = res.data.msg.order.pack
        this.listData.orderSn = res.data.msg.hireSn
        this.listData.totalPayPrice = res.data.msg.hirePrice
      })
    }

    if (this.firstPayBool) { // 第一次进来付款不用去查询有没有支付
      this.setFirstPayBool(false)
    } else {  // 其他支付失败后再进行支付
      orderPaySuccess(this.orderSnNum).then(res => {
        if (res.data.remarks == '0') { // 刷新时查看是否成功 0 是成功
          this.$alert('该订单已完成支付', '提示', {
            confirmButtonText: '确定',
            showClose: false,
            callback: action => {
              this.$router.push({
                path: '/personal',
                query: { flag: '1' }
              })
              this.setFirstPayBool(true)
            }
          });
          return
        }
      })
    }

  },
  methods: {
    ...mapActions(['setFirstPayBool']),
    togglePayConfirm() {
      this.payConfirm = false;
    },
    countConsult(){
      let userId = this.currentUser && this.currentUser.cluesOrStuId || '',
        account = this.currentUser && this.currentUser.account || '',
        cityId = this.cityId && this.cityId || '',
        cityName = this.cityName && this.cityName || ''

      statisticsSave(cityId, cityName, userId, account)
    },
    getOrderDetail() {
      orderDetail(this.$route.query.orderSn).then(res => {
        this.listData = res;
        this.pack = res.pack;
        this.dataTime = this.listData.createdAt
      })
    },
    changePayConfirmFn(bool) {
      this.payConfirm = bool
    },
    paySucceeBool() {
      // this.$refs.confrimData.centerDialogVisible = true
      if (this.payStyle.wechatBool) {
        this.$router.push({
          name: 'wechatPage',
          params: {
            price: this.$route.params.listData.price
          }
        })
      }
    },
    changeFn(name) {
      for (let key in this.payStyle) {
        this.$set(this.payStyle, key, false)
      }
      this.$set(this.payStyle, name, true)
    },
    createPayOrderFn() {
      
      // var tempwindow = window.open('about:blank','_self');
      createPayOrder(this.listData.orderSn, Number(this.listData.totalPayPrice) * 100, this.User.cluesOrStuId).then(res => {
        return res.out_trade_no;
      }).then(no => {
        this.loadingBool = false
        if (this.payStyle.wechatBool) {
          createPolymPay(no,Number(this.listData.totalPayPrice) * 100,'WeixinXMZH').then(data=>{
            let routeData = this.$router.resolve({
              path: "/wechatPage",
              query: {
                code_url: data.data.trade_qrcode,
                total: this.listData.totalPayPrice,
                no: no,
                courseId:this.$route.query.courseId  //传课程Id
              }
            });
            this.payLoding.close()
            // var tempwindow = window.open('about:blank','_self');
            let url = 'https://' + window.location.host + routeData.href;
            // tempwindow.location.href = url;
            window.open(url,'_self')
          })
          // createWechatPay(no, this.pack.brief, this.pack.detail, this.listData.totalPayPrice + '00', this.User.cluesOrStuId).then(data => {
          // createWechatPay(no, '国科学院-套餐课程付费',  this.pack.name, Number(this.listData.totalPayPrice) * 100, this.User.cluesOrStuId).then(data => {
          //   let routeData = this.$router.resolve({
          //     path: "/wechatPage",
          //     query: {
          //       code_url: data.code_url,
          //       total: this.listData.totalPayPrice,
          //       no: no,
          //       courseId:this.$route.query.courseId  //传课程Id
          //     }
          //   });
          //   this.payLoding.close()
          //   // window.open(routeData.href, '_blank');
          //   var tempwindow = window.open('about:blank','_self');
          //   let url = 'https://' + window.location.host + routeData.href;
          //   tempwindow.location.href = url;
          // })
        } else if(this.payStyle.alipayBool){
          createPolymPay(no,Number(this.listData.totalPayPrice) * 100,'AlipayNXMZ').then(data=>{
            let routeData = this.$router.resolve({
              path: "/alipayPage",
              query: {
                code_url: data.data.trade_qrcode,
                total: this.listData.totalPayPrice,
                no: no,
                courseId:this.$route.query.courseId  //传课程Id
              }
            });
            this.payLoding.close()
            // var tempwindow = window.open('about:blank','_self');
            let url = 'https://' + window.location.host + routeData.href;
            // tempwindow.location.href = url;
            window.open(url,'_self')
          })

          // createAliPay(no, '', this.pack.name, Number(this.listData.totalPayPrice) * 100, this.User.cluesOrStuId,this.$route.query.courseId).then(data => {
          //   this.loadingBool = false
          //   // const div = document.createElement('div');
          //   // div.innerHTML = data.html;
          //   // document.body.appendChild(div);
          //   // document.forms[document.forms.length - 1].target = "_blank";
          //   // document.forms[document.forms.length - 1].submit();
          //   this.payLoding.close()
          //   var tempwindow = window.open('about:blank','_blank');
          //   tempwindow.location = document.location;
          //   const div = tempwindow.document.createElement('div');
          //   div.innerHTML = data.html;
          //   tempwindow.document.body.appendChild(div);
          //   tempwindow.document.forms[tempwindow.document.forms.length - 1].acceptCharset = "utf-8";
          //   tempwindow.document.forms[tempwindow.document.forms.length - 1].onsubmit = "document.charset='utf-8'";
          //   tempwindow.document.forms[tempwindow.document.forms.length - 1].submit();
          // })
        }else{
          let that=this
          createYiwtPay(no, '', this.pack.name, Number(this.listData.totalPayPrice) * 100, this.User.cluesOrStuId,this.$route.query.courseId).then(data=>{
            let jsData=JSON.stringify(data.jsonRequestData)
            let routeData = this.$router.resolve({
              path: "/ywtpayPage",
              query: {
                payurl:data.payurl,
                jsoData:jsData
              }
            });
            this.payLoding.close()
            // var tempwindow = window.open('about:blank','_self');
            let url = 'https://' + window.location.host + routeData.href;
            // tempwindow.location.href = url;
            window.open(url,'_self')
          })
        }
      })
    },
    createPayOrder() {
      this.loadingBool = true
      if (this.payStyle.alipayBool || this.payStyle.wechatBool || this.payStyle.yiwtpayBool) {
        // this.payConfirm = true;
        this.payLoding = this.getLoading(' ')
        this.createPayOrderFn()
      } else {
        this.loadingBool = false
        this.$alert('请选择一种付款方式', '付款方式', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      }
    },
    openOtherpay(){
      if(this.ywtPay==false){
        this.ywtPay=true
      }else{
        this.ywtPay=false
      }
    }
  },
  components: {
    confirmPay,
    payError
  }
}

</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
@import '~style/base.styl';

.pay-content-wrapper {
  width: 1200px;
  padding-bottom: 50px;
  margin: 120px auto 0;
  background-color: $color-text;

  .pay-details-wrapper {
    padding: 0 0 50px 0;
    margin: 50px 0 0 180px;

    .stages-wrapper {
      color: $color-person-text;
      font-size: $font-size-medium;

      span {
        color: $color-background;
        margin-right: 25px;
      }

      .now-stages {
        margin-top: 20px;
      }
    }
  }
}

// 时间与订单
.pay-details-top {
  .time-limit {
    @extend .clear-default;
    height: 15px;
    color: $color-text-m;
    font-size: $font-size-large-l;
    text-align: justify;
    font-size: 14px;

    .time {
      margin: 0 8px;
      color: $color-pay-text;
    }
  }

  .pay-list {
    margin-top: 15px;
    font-size: 14px;
    color: #767676;

    span + span {
      margin-left: 30px;
    }
  }
}

.pay-price {
  margin-top: 60px;
  font-size: 20px;
  color: $color-pay-text;

  .yuan {
    font-size: 14px;
    margin-left: 9px;
    color: #767676;
  }
}

// 支付方式
.pay-way-wrapper {
  margin-top: 30px;

  .text {
    @extend .clear-default;
    height: 20px;
    text-align: left;
    font-size: $font-size-large-l;
    color: $color-background;
    line-height: 20px;
  }

  .pay-icon-wrapper {
    margin-top: 20px;

    &:after {
      content: '';
      display: block;
      clear: both;
    }
    .align
    {
      width:100%;
      display:inline-block
    }
    .top
    {
      margin-top:20px
    }
    .payyl
    {
      font-size: 12px;
      font-family: MicrosoftYaHei;
      font-weight: 400;
      color: rgba(118,118,118,1);
      margin-top: 9px;
    }
    .alipay, .wechat{
      position: relative;
      float: left;
      width: 166px;
      height: 44px;
      border: 1px solid #ccc;
      background-color: rgba(245, 245, 245, 1);
      text-align: center;
      line-height: 44px;
      font-size: $font-size-large-l;
      color: $color-text-m;
      border-radius: 2px;
      cursor: pointer;
      -webkit-transition: all 0.5s;
      -moz-transition: all 0.5s;
      -o-transition: all 0.5s;
      -ms-transition: all 0.5s;
      transition: all 0.5s;

      .icon-pic{
        margin-top:7.5px
      }
      .icon {
        display: inline-block;
        width: 30px;
        height: 30px;
        margin-right: 6px;
        margin-left:20px;
        vertical-align: -5px;
        font-size: 30px;
      }
      .tuij{
        position:absolute;
        left:0;
        width: 34px;
        height: 32px;
      }
      .topIcon {
        position: absolute;
        top: 0;
        right: -1px;
        width: 12px;
        height: 12px;
        opacity: 0;
        filter: Alpha(opacity: 0);
        font-size: 12px;
        -webkit-transition: all 0.5s;
        -moz-transition: all 0.5s;
        -o-transition: all 0.5s;
        -ms-transition: all 0.5s;
        transition: all 0.5s;
      }
      
    }
    .otherPay{
      margin-bottom:10px;
      display: flex;
      align-items: center;
      font-size: 12px;
      font-family: MicrosoftYaHei;
      font-weight: 400;
      .roate{
        transform:rotate(-180deg)
      }
      .icon-xiaosan_n{
        display: inline-block;
        transform:scale(0.6)
      }
    }
    .yiwtpay{
      position: relative;
      width: 187px;
      height: 40px;
      border: 1px dashed #ff6252;
      text-align: center;
      line-height: 44px;
      font-size: 14px;
      color: #202020;
      border-radius: 2px;
      cursor: pointer;
      -webkit-transition: all 0.5s;
      transition: all 0.5s;
      display: flex;
      align-items: center;
      img{
        width: 29px;
        height: 29px;
        margin: 0 5px 0 21px;
      }
      .icon {
        display: inline-block;
        width: 30px;
        height: 30px;
        margin-right: 16px;
        vertical-align: -5px;
        font-size: 30px;
      }

      .topIcon {
        position: absolute;
        top: 0;
        right: -1px;
        width: 12px;
        height: 12px;
        opacity: 0;
        filter: Alpha(opacity: 0);
        font-size: 12px;
        -webkit-transition: all 0.5s;
        -moz-transition: all 0.5s;
        -o-transition: all 0.5s;
        -ms-transition: all 0.5s;
        transition: all 0.5s;
      }
    }

    .wechat {
      margin-left: 30px;
    }

    .alipay.on, .wechat.on, .yiwtpay.on {
      border: 1px solid #ff6252;
    }

    .alipay.on .topIcon, .wechat.on .topIcon, .yiwtpay.on .topIcon {
      opacity: 1;
      filter: Alpha(opacity: 100);
    }
  }
}

// 提交按钮
.btn-wrapper {
  
}
.btnwrap{
  margin-top: 60px;
}
.btnwrap2{
  margin-top:10px
}
.btn-wrapper .submit, .btn-wrapper .consult {
  display: inline-block;
  width: 144px;
  height: 44px;
  background-color: $color-text;
  border: 1px solid $color-sub-pay;
  text-align: center;
  border-radius: 2px;
  text-decoration: none;
  color: $color-sub-pay;
  cursor: pointer;
}

.btn-wrapper .consult {
  line-height: 44px;
  background: #FFEFED;
  border: 1px solid #FF6252;
  margin-left: 30px;
}

.btn-wrapper .submit {
  line-height: 44px;
  background-color: rgba(255, 98, 82, 1);
  opacity: 0.5;
  color: $color-text;
  border: 1px solid $color-sub-pay;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  -o-transition: all 0.5s;
  -ms-transition: all 0.5s;
  transition: all 0.5s;

  span {
    line-height: 12px;
  }
}

.btn-wrapper .submit.checkColor {
  opacity: 1;
  filter: Alpha(opacity: 100);
}
</style>
